package com.shensi.adminCollect.service.station.impl;

import com.shensi.common.core.domain.entity.SysUser;
import com.shensi.common.core.domain.model.LoginUser;
import com.shensi.common.core.utils.SecurityUtils;
import com.shensi.adminCollect.domain.station.Repository;
import com.shensi.adminCollect.mapper.station.RepositoryMapper;
import com.shensi.adminCollect.service.station.RepositoryService;
import com.shensi.adminCollect.utils.station.CodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service("repositoryService")
@Slf4j
public class RepositoryServiceImpl implements RepositoryService {

    @Autowired
    private RepositoryMapper repositoryMapper;

    @Override
    public int saveRepository(Repository repository) {
        int i = 0;
        synchronized (this){
            String code = null;
            boolean flag = true;
            // 校验 重复
            while (flag) {
                code = CodeUtil.createCode();
                Repository result = repositoryMapper.selectByRepositoryCode(code);
                if(Objects.isNull(result)){
                    flag = false; // 终止循环
                }
            }
            repository.setRepositoryCode(code);
            i = repositoryMapper.insertSelective(repository);
        }
        return i;
    }

    @Override
    public List<Repository> selectRepositoryList(Repository repository) {
        return repositoryMapper.selectRepositoryList(repository);
    }

    @Override
    public Repository selectOneRepository(Repository repository) {
        return repositoryMapper.selectOneRepository(repository);
    }

    @Override
    public int updateRepository(Repository repository) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        repository.setUpdateUser(sysUser.getUserId());
        repository.setUpdateTime(new Date());
        return repositoryMapper.updateByPrimaryKeySelective(repository);
    }

    @Override
    public int deleteRepository(List<Long> repositoryIdList) {
        return repositoryMapper.deleteRepository(repositoryIdList);
    }
}
